{% extends "base.html" %}

{% block title %}忘记密码{% endblock %}

{% block content %}
<div class="d-flex justify-content-center align-items-center vh-100">
    <div class="card p-4" style="width: 22rem;">
        <h1 class="text-center mb-4">忘记密码</h1>

        <form name="forgotPasswordForm" action="{{ url_for('forgot_password') }}" method="POST"
              onsubmit="return validateForm()">
            <div class="mb-3">
                <label for="username" class="form-label">用户名</label>
                <input type="text" name="username" id="username" class="form-control" required>
            </div>

            <!-- 展示半脱敏的邮箱地址 -->
            <div class="mb-3">
                <label class="form-label">注册邮箱</label>
                <p id="email-display" class="form-control-plaintext">请输入用户名以显示注册邮箱</p>
            </div>

            <button type="submit" class="btn btn-primary w-100">发送邮件</button>
        </form>

        <div class="text-center mt-3">
            <a href="{{ url_for('login') }}" class="link-secondary">返回登录</a>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('#username').on('input', function() {
        let username = $(this).val();

        if (username) {
            $.ajax({
                url: "{{ url_for('get_email') }}",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({username: username}),
                success: function(response) {
                    if (response.email) {
                        $('#email-display').text(response.email);  // 显示返回的半脱敏邮箱
                    } else {
                        $('#email-display').text("未找到对应的注册邮箱");
                    }
                },
                error: function() {
                    $('#email-display').text("出现错误，请稍后再试");
                }
            });
        } else {
            $('#email-display').text("请输入用户名以显示注册邮箱");
        }
    });
});
</script>
{% endblock %}
